<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="名称" prop="name">-->
<!--        <el-input-->
<!--          v-model="queryParams.name"-->
<!--          placeholder="请输入名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="起始时间">
        <el-date-picker
          v-model="queryParams.dateQuery"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="上报用户" prop="reportUserId">

        <el-select clearable  v-model="queryParams.reportUserId" filterable placeholder="选择上报用户" >
          <el-option
            v-for="user in filteredUsers"
            :key="user.userId"
            :label="user.nickName"
            :value="user.userId">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="部门" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="deptOptions"
          :show-count="true"
          placeholder="请选择归属部门"
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['depot:depot:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['depot:depot:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['depot:depot:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['depot:depot:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="depotList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="deptName"  />
      <el-table-column label="数据日期" align="center" prop="name"  />
      <el-table-column label="收油数量(车)" align="center" prop="collectCount"  />
      <el-table-column
        label="收入油库"
        align="center"
        prop="collectType"
        :formatter="formatCollectType"
      />

      <el-table-column label="收油重量(吨)" align="center" prop="collectWeight"  />
      <el-table-column label="发油信息" align="center" prop="sendInfo"  />
      <el-table-column
        label="工作人员"
        align="center"
        prop="workUserId"
        :formatter="workUserIdFormat"
        show-overflow-tooltip
      >
        <template slot-scope="{ row, column, $index }">
          <span v-html="workUserIdFormat(row, column, row.workUserId)"></span>
        </template>
      </el-table-column>
      <el-table-column label="前日迎检情况" align="center" prop="info"  />
      <el-table-column label="异常情况" align="center" prop="error"  />
      <el-table-column label="汇报人" align="center" prop="reportUserId" :formatter="reportUserIdFormat" />


<!--      <el-table-column label="现存油可用天数" align="center" prop="days"  />-->
      <el-table-column label="自提油情况" align="center" prop="selfInfo"  />
      <el-table-column label="上报时间" align="center" prop="reportDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['depot:depot:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['depot:depot:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改油库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="数据日期" prop="name" v-dialog-drag-width="200">
              <el-date-picker
                v-model="form.name"
                type="date"
                placeholder="请输入数据日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="近7天用油量" >
              <el-input disabled v-model="avgOil" placeholder="请输入近7天用油量"  style="width: 190px" >
                <template slot="append">(吨)</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="存油可用天数" prop="days">
              <el-input disabled v-model="form.days" placeholder="请输入现存油可用天数"  style="width: 190px" >
                <template slot="append">(天)</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
<el-row :gustter="24">
  <el-col :span="8">
    <el-form-item label="收油数量(车)" prop="collectCount">
      <el-input-number :min="0" :precision="0" :step="1" v-model="form.collectCount" placeholder="请输入收油数量(车)"/>

    </el-form-item>
  </el-col>
  <el-col :span = "8">
    <el-form-item label="收油重量(吨)" prop="collectWeight">
      <el-input-number :min="0" :precision="3" v-model="form.collectWeight" placeholder="请输入收油重量" />
    </el-form-item>

  </el-col>
  <el-col :span="8">
    <el-form-item label="收入油库" prop="collectType">
      <el-select v-model="form.collectType" placeholder="请选择"  @change="handleCollectTypeChange">
        <el-option label="旧库" :value=0></el-option>
        <el-option label="新库" :value=1></el-option>
      </el-select>
    </el-form-item>
  </el-col>


</el-row >

            <el-divider content-position="center">发油信息</el-divider>
            <el-form-item >

              <div v-for="(item, index) in form.sendJson" :key="index">
                <el-row :gutter="24">
                  <el-col :span="10">
                    <el-form-item :label="'储油罐 ' + (index + 1)" :prop="'from' + index">
                      <el-select v-model="item.from" placeholder="请选择储油罐"   @change="handleFromChange(item)" clearable size="small">
                        <el-option
                          v-for="dict in filterdOilUsedTanks"
                          :key="dict.id"
                          :label="dict.name "
                          :value="dict.id"

                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item :label="'重量(吨) '" :prop="'weight' + index">
                      <el-input-number v-model="item.weight" placeholder="请输入重量" :precision="4"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <!--            <el-col :span="7">-->
                  <!--              <el-form-item :label="'数量(车) '" :prop="'count' + index">-->
                  <!--                <el-input-number v-model="item.count" placeholder="请输入数量(车)" :precision="0" :min="0" :step="1"></el-input-number>-->
                  <!--              </el-form-item>-->
                  <!--            </el-col>-->

                  <el-col :span="4"  class="row-actions">
                    <el-button
                      type="danger"
                      icon="el-icon-minus"
                      @click="removeDensityRow(index)"
                      :disabled="form.sendJson&&form.sendJson.length <=1"
                      circle
                      style="margin-left: 10px;">
                    </el-button>
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      @click="addDensityRow"
                      :disabled="form.sendJson&&form.sendJson.length >= 5"
                      circle>
                    </el-button>
                  </el-col>

                </el-row>
              </div>

            </el-form-item>
            <el-form-item label="发油信息" prop="sendInfo">
              <el-input readonly type="textarea" v-model="form.sendInfo" placeholder="请输入发油信息" />
            </el-form-item>

<el-row :gustter="20">
  <el-col :span = "10">
    <el-form-item  label="工作人员" prop="workUsers">


      <el-select clearable multiple  v-model="form.workUsers" filterable placeholder="选择工作人员"  style="width: 200px">
        <el-option
          v-for="user in filteredUsers"
          :key="user.userId"

          :label="user.nickName "
          :value="user.userId">
        </el-option>
      </el-select>

    </el-form-item>
  </el-col>
</el-row>



        <el-form-item label="前日迎检情况" prop="info">
          <el-input v-model="form.info" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="异常情况" prop="error">
          <el-input v-model="form.error" type="textarea" placeholder="请输入异常情况" />
        </el-form-item>




        <el-divider content-position="center">油罐信息详情信息</el-divider>
        <el-table :data="reportOilDepotDetailList" :row-class-name="rowReportOilDepotDetailIndex"
                  @selection-change="handleReportOilDepotDetailSelectionChange" ref="reportOilDepotDetail">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>

          <el-table-column label="储罐" prop="tankId" header-align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.tankId"
                placeholder="请选择储罐"
                disabled
                clearable
                size="small"
                class="center-select"
                style="width: 100%"
              >
                <el-option
                  v-for="tank in availableTanks[scope.$index] || []"
                  :key="tank.id"
                  :label="tank.name"
                  :value="tank.id"
                />
              </el-select>
            </template>
          </el-table-column>


          <el-table-column label-class-name="text-center" label="油高(米)" prop="tankHeight">
            <template slot-scope="scope">
              <div
                :style="{ border: '4px solid',borderColor: (scope.row.tankType==3&&scope.row.tankHeight >= scope.row.baojingHeight) ? 'red': (scope.row.tankType==3&&scope.row.tankHeight >= scope.row.yujingHeight)? 'yellow': 'transparent',padding: '4px',borderRadius: '4px'}"
              >
                <el-input-number
                  style="width: 100%; background-color: transparent;"
                  :min="0"
                  :precision="4"
                  v-model="scope.row.tankHeight"
                  placeholder="请输入高度(米)"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column label-class-name="text-center" label="库存(吨)" prop="tankWeight">
            <template slot-scope="scope">
              <el-input-number     style="width: 100%" :min="0" :precision="4" v-model="scope.row.tankWeight" placeholder="请输入库存(吨)"/>
            </template>
          </el-table-column>

          <el-table-column label-class-name="text-center" label="储罐使用状态" prop="tankStatus">

            <template slot-scope="scope">
              <el-select      style="width: 100%"    class="center-select" v-model="scope.row.tankStatus" placeholder="请输入储罐使用状态" clearable size="small">
                <el-option
                  v-for="dict in filteredStatusOptions(scope.row.tankType)"
                  :key="dict.dictValue"
                  :label="dict.dictLabel "
                  :value="dict.dictValue"
                />
              </el-select>

            </template>
          </el-table-column>
          <el-table-column label-class-name="text-center" label="化验单编号" prop="sheetNo">
            <template slot-scope="scope">
              <el-input     style="width: 100%" v-model="scope.row.sheetNo" placeholder="请输入化验单编号"/>
            </template>
          </el-table-column>


        </el-table>
        <el-divider content-position="center">自提油信息详情信息</el-divider>
        <el-form-item>

          <div v-for="(item, index) in form.extra1" :key="index">
            <el-row :gutter="24">
              <el-col :span="7">
                <el-form-item :label="'客户 ' + (index + 1)" :prop="'from' + index">
                  <el-select v-model="item.from" placeholder="请选择自提油客户" @change="handleKhChange(item)" clearable
                             size="small">
                    <el-option
                      v-for="dict in filterdKh"
                      :key="dict.id"
                      :label="dict.name "
                      :value="dict.id"

                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="7">
                <el-form-item :label="'重量(吨) '" :prop="'weight' + index">
                  <el-input-number v-model="item.weight" placeholder="请输入重量" :precision="4" :min="0"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item :label="'数量(车) '" :prop="'count' + index">
                  <el-input-number v-model="item.count" placeholder="请输入数量(车)" :precision="0" :min="0"
                                   :step="1"></el-input-number>
                </el-form-item>
              </el-col>

              <el-col :span="3"  class="row-actions">
                <el-button
                  type="danger"
                  icon="el-icon-minus"
                  @click="removeKhRow(index)"
                  :disabled="form.extra1&&form.extra1.length <=1"
                  circle
                  style="margin-left: 10px;">
                </el-button>
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  @click="addKhRow"
                  :disabled="form.extra1&&form.extra1.length >= 5"
                  circle>
                </el-button>
              </el-col>
            </el-row>
          </div>

        </el-form-item>

        <el-form-item label="自提油情况" prop="selfInfo">
          <el-input readonly v-model="form.selfInfo" type="textarea" placeholder="请输入自提油情况" />
        </el-form-item>




        <el-form-item  label="汇报人员" prop="reportUserId">
          <el-select clearable  v-model="form.reportUserId" filterable placeholder="选择汇报人员" >
            <el-option
              v-for="user in filteredUsers"
              :key="user.userId"

              :label="user.nickName "
              :value="user.userId">
            </el-option>
          </el-select>

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDepot, getDepot, delDepot, addDepot, updateDepot, exportDepot } from "@/api/depot/depot";
import { listUserNoPage } from '@/api/system/user'
import { listTankNoPage } from '@/api/oiltank/tank'
import Treeselect from '@riophae/vue-treeselect'
import { treeselect } from '@/api/system/dept'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listSelfPickup, listSelfPickupNoPage } from '@/api/report/selfPickup'
import { listStationNoAuth, listStationNoAuthNoPage } from '@/api/station/station'

export default {
  name: "Depot",
  components: { Treeselect },
  data() {
    return {
      avgOil:0,
      avgList:[],
      filterdOilUsedTanks:[],
      filterdKh:[],
      message:'',
      statusOptions:[],
      deptOptions:[],
      filterdOilTanks:[],
      filteredUsers:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      availableTanks:[],
      // 子表选中数据
      checkedReportOilDepotDetail: [],
      // 非单个禁用
      single: true,
      currentDate: new Date() ,// 获取当前日期
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      stationList:[],
      // 油库表格数据
      depotList: [],
      // 油罐信息详情表格数据
      reportOilDepotDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // id字典
      idOptions: [],
      // 名称字典
      nameOptions: [],
      // 收油数量字典
      collectCountOptions: [],
      // 发油信息字典
      sendInfoOptions: [],
      // 工作人员字典
      workUserIdOptions: [],
      // 异常情况字典
      errorOptions: [],
      // 创建人字典
      createByOptions: [],
      // 汇报人字典
      reportUserIdOptions: [],
      // 创建时间字典
      createTimeOptions: [],
      // 修改人字典
      updateByOptions: [],
      // 修改时间字典
      updateTimeOptions: [],
      // extra1字典
      extra1Options: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      workUsers:[],
      // extra2字典
      extra2Options: [],
      // extra3字典
      extra3Options: [],
      // extra4字典
      extra4Options: [],
      // 部门字典
      deptIdOptions: [],
      // 前日迎检情况字典
      infoOptions: [],
      // 收油重量字典
      collectWeightOptions: [],
      // 现存油可用天数字典
      daysOptions: [],
      // 自提油情况字典
      selfInfoOptions: [],
      // 发油情况json字典
      sendJsonOptions: [],
      // 查询参数
      queryParams: {
        dateQuery:[],
        pageNum: 1,
        pageSize: 10,
        name: null,
        workUserId: null,
        reportUserId: null,
        deptId: null,
        info: null,
        collectWeight: null,
        days: null,
        selfInfo: null,
      },
      // 表单参数
      form: {
        sendJson:[{
          from:'',
          fromName:'',
          to:'',
          toName:'',
          weight:'',count:0
        }],
        collectType:0,
        extra1:[{
          from:'',
          fromName:'',
          weight:'',
          count:0
        }

        ]
      },
      // 表单校验
   rules:{
     // collectCount: [
     //   { required: true, message: "收油数量不能为空", trigger: "blur" },
     //   { type: 'number', message: "收油数量必须为数字", trigger: "blur" }
     // ],
     // 发油信息
     // sendInfo: [
     //   { required: true, message: "发油信息不能为空", trigger: "blur" }
     // ],
     collectType:[
       { required: true, message: "收入油库不能为空", trigger: "blur" }
     ],
     name: [
       { required: true, message: "名称不能为空", trigger: "blur" }
     ],
     // 工作人员
     // workUserId: [
     //   { required: true, message: "工作人员不能为空", trigger: "blur" }
     // ],
     workUsers: [
       { required: true, message: "工作人员不能为空", trigger: "blur" }
     ],
     // 异常情况

     // 汇报人
     reportUserId: [
       { required: true, message: "汇报人不能为空", trigger: "blur" }
     ],
     // 前日迎检情况

     // 收油重量
     // collectWeight: [
     //   { required: true, message: "收油重量不能为空", trigger: "blur" },
     //   { type: 'number', message: "收油重量必须为数字", trigger: "blur" }
     // ],

     // 上报时间
     reportDate: [
       { required: true, message: "上报时间不能为空", trigger: "change" }
     ],
     reportOilDepotDetailList: [
       {
         type: 'array',
         required: true,
         message: '请添加至少一条储油罐详情信息',
         trigger: 'change'
       },
       {
         validator: this.validateDetailList,
         trigger: 'change'
       }]
   }
    };
  },
  created() {
    const routeDeptId = this.$route.query.deptId || null
    this.queryParams.deptId = routeDeptId
    this.getList();
    this.fetchUsers()

    this.getTreeselect()

    this.getDicts('oil_tank_status').then(response => {
      this.statusOptions = response.data
    // let   allowedValues = ['1', '2', '3', '4']
    //   this.statusOptions = response.data.filter(item => allowedValues.includes(item.dictValue))
    })
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.nameOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.collectCountOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.sendInfoOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.workUserIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.errorOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.reportUserIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateByOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.updateTimeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra1Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra2Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra3Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extra4Options = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.deptIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.infoOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.collectWeightOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.daysOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.selfInfoOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.sendJsonOptions = response.data;
    });
  },
  watch: {

    reportOilDepotDetailList: {
      handler(newVal) {
        // 获取当前已选择的 tankId
        const selectedTankIds = newVal.map(item => item.tankId);

        // 遍历每行明细，并动态更新每行的可选油罐
        newVal.forEach((item, index) => {
          this.$set(this.availableTanks, index, this.filterdOilTanks.filter(
            tank => !selectedTankIds.includes(tank.id) || tank.id === item.tankId
          ));
        });

        // 如果超过油罐数量，截断列表并提示
        if (newVal.length > this.filterdOilTanks.length) {
          this.reportOilDepotDetailList.splice(this.filterdOilTanks.length);
          this.$message.error(`明细数量不能超过油罐数量 (${this.filterdOilTanks.length})`);
        }
      },
      deep: true
    },


    // 深度监听整个 sendJson 数组
    'form.sendJson': {
      handler(newVal) {
        // 如果 sendJson 为空或长度为 0，不处理
        if (!newVal || newVal.length === 0) {
          this.form.sendInfo = ''; // 确保 sendInfo 也被清空
          return;
        }

        const infoList = newVal.map(item => {
          const { from, to, weight,toName,fromName,count } = item;

          if (from && weight) {
            if (to && from === to) {
              // 如果 from 和 to 相同，提示不能相同
              this.$modal.msgError("储油罐和经转储油罐不能是同一个");
              item.to=null

            } else if (to) {
              // 如果 to 有值且不相同，拼接转罐信息
              if (count&&count>0){
                return `[${fromName}] 经转 ${toName}号罐 发 ${weight} 吨, 共计 ${count} 车`;
              }else {
                return `[${fromName}] 经转 ${toName}号罐 发 ${weight} 吨`;
              }

            } else {
              if (count&&count>0){
                return `[${fromName}] 发 ${weight} 吨, 共计 ${count} 车`;
              }else {
                return `[${fromName}] 发 ${weight} 吨`;
              }
              // 如果 to 没有值，拼接普通罐发信息

            }
          }
          return ''; // 如果不满足条件，返回空字符串
        }).filter(Boolean); // 过滤掉空字符串

        // 将所有结果用 `;` 拼接
        this.form.sendInfo = infoList.length > 0 ? infoList.join(' 转 ') : '';
      },
      deep: true // 深度监听
    },

    'form.extra1': {
      handler(newVal) {
        // 如果 sendJson 为空或长度为 0，不处理
        if (!newVal || newVal.length === 0) {
          this.form.selfInfo = ''; // 确保 sendInfo 也被清空
          return;
        }

        const infoList = newVal.map(item => {
          const { from, fromName, weight,count } = item;

          if (from && weight&&count) {

              // 如果 to 有值且不相同，拼接转罐信息
              return `客户[${fromName}] 自提 ${weight} 吨, 共计 ${count} 车`;

          }
          return ''; // 如果不满足条件，返回空字符串
        }).filter(Boolean); // 过滤掉空字符串

        // 将所有结果用 `;` 拼接
        this.form.selfInfo = infoList.length > 0 ? infoList.join(' 转 ') : '';
      },
      deep: true // 深度监听
    }
  },
  methods: {
    handleCollectTypeChange(value) {
      console.log('切换为：', value);
    },
    updateTankType(row) {
      // 根据选中的 tankId 找到对应的油罐类型
      const selectedTank = this.filterdOilTanks.find(tank => tank.id === row.tankId);

      // 如果找到了油罐，更新 tankType
      if (selectedTank) {
        row.tankType = selectedTank.typeId+''; // 假设你的油罐对象有一个 typeId 属性
      } else {
        row.tankType = null; // 如果没有选择有效的油罐，清空类型
      }
      console.log('row')
      console.log(row)
      // 更新状态，确保状态是最新的
      row.tankStatus = null; // 清空状态，以便重新选择
    },
    filteredStatusOptions(type) {
      console.log('Input type:', type);

      const allowedValues = (Number(type) === 3||Number(type) === 4) ? [4,5] : [1,2,3,4];
      console.log('Allowed values:', allowedValues);

      const filtered = this.statusOptions.filter(item => {
        const itemValue = Number(item.dictValue); // 将 dictValue 转换为数字
        console.log('Checking item:', item.dictValue, 'Converted to:', itemValue);
        return allowedValues.includes(itemValue);
      });

      console.log('Filtered results:', filtered);
      return filtered;
    },
    validateDetailList(rule, value, callback) {
      // if (!value || value.length === 0) {
      //   return callback(new Error('请至少添加一条明细'));
      // }

      // 遍历明细列表，逐一检查每个字段
      for (let i = 0; i < value.length; i++) {
        let detail = value[i];
        if (!detail.tankId) {
          return callback(new Error('第 ' + (i + 1) + ' 行的储油罐不能为空'));
        }
        // if (!detail.tankWeight) {
        //   return callback(new Error('第 ' + (i + 1) + ' 行的储油罐重量不能为空'));
        // }
        // if (!detail.tankHeight) {
        //   return callback(new Error('第 ' + (i + 1) + ' 行的储油罐高度不能为空'));
        // }
        if (!detail.tankStatus) {
          return callback(new Error('第 ' + (i + 1) + ' 行的储油罐状态不能为空'));
        }

if(detail.tankStatus=='1'&&(!detail.sheetNo||''==detail.sheetNo)){
  return callback(new Error('第 ' + (i + 1) + ' 行的储油罐状态为发油,化验单号必填'));
}

      }
      // 验证通过
      callback();
    },


    fetchKh(){
      listSelfPickupNoPage({ } ).then(response => {
      this.filterdKh=response.rows;
      });
    },
    // 处理储油罐选择变化的函数
    handleFromChange(item) {
      const selectedOilTank = this.filterdOilTanks.find(tank => tank.id === item.from);

      if (selectedOilTank) {
        item.fromName = selectedOilTank.name; // 自动填充储油罐的名称
      } else {
        item.fromName = ''; // 如果没有选择有效罐，清空名称
      }
    },
    handleKhChange(item) {
      const kh = this.filterdKh.find(tank => tank.id === item.from);

      if (kh) {
        item.fromName = kh.name;
      } else {
        item.fromName = '';
      }
    },

    handleToChange(item) {
      const selectedOilTank = this.filterdOilTanks.find(tank => tank.id === item.to);

      if (selectedOilTank) {
        item.toName = selectedOilTank.name; // 自动填充储油罐的名称
      } else {
        item.toName = ''; // 如果没有选择有效罐，清空名称
      }
    },
    addDensityRow() {
      if (!Array.isArray(this.form.sendJson)) {
        this.$set(this.form, 'sendJson', []);
      }

      this.form.sendJson.push({ from: '', to: '', weight: '',count:0 }); // 添加新行
    },
    removeDensityRow(index) {

      if (this.form.sendJson.length > 1) {
        this.form.sendJson.splice(index, 1);
      }
    },
    addKhRow() {
      if (!Array.isArray(this.form.extra1)) {
        this.$set(this.form, 'extra1', []);
      }

      this.form.extra1.push({ from: '',  weight: '',count:0 }); // 添加新行
    },
    removeKhRow(index) {

      if (this.form.extra1.length > 1) {
        this.form.extra1.splice(index, 1);
      }
    },


    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
    },
    fetchOilTanks() {
      listTankNoPage({auth:true}).then(response => {
        this.filterdOilTanks = response.rows
        this.filterdOilUsedTanks = response.rows.filter(tank => tank.typeId !== 3);


        if (!this.form.id){
          this.filterdOilTanks.forEach(tank => {
            let obj = {};
            obj.extra1 = "";
            obj.extra2 = "";
            obj.extra3 = "";
            obj.extra4 = "";
            obj.deptId = "";
            obj.tankId = tank.id;
            obj.tankWeight = tank.weight != null ? tank.weight : 0; // 确保 weight 为空时为 0
            obj.tankHeight = tank.height != null ? tank.height : 0; // 确保 height 为空时为 0
            obj.tankStatus = tank.status+"";
            obj.tankType = tank.typeId+'';
            obj.yujingHeight = tank.extra1 + ''
            obj.baojingHeight = tank.extra2 + ''
            obj.sheetNo = "";
            this.reportOilDepotDetailList.push(obj);
          });
        }
          // 初始化一个变量来存储累加结果
          let totalOilUsed = 0;

// 遍历 this.filterdOilUsedTanks 数组
          this.filterdOilUsedTanks.forEach(tank => {
            // 获取 weight 和 min_cap 的值
            let weight = tank.weight || 0;  // 假设字段存在，如果不存在则默认为 0
            let minCap = tank.minCap || 0; // 同理，默认值为 0

            // 将 weight 减去 min_cap 并累加到 totalOilUsed
            totalOilUsed += (weight - minCap);
          });

          listStationNoAuthNoPage().then(response => {
            this.stationList = response.rows;
            // 获取当前日期
            const today = new Date();

// 计算最近七天的日期
            const sevenDaysAgo = new Date();
            sevenDaysAgo.setDate(today.getDate() - 7);

// 筛选出 reportDate 在最近七天内的数据
            this.avgList = this.stationList.filter(station => {
              const reportDate = new Date(station.reportDate);
              return reportDate >= sevenDaysAgo && reportDate <= today;
            });

// 计算最近七天的总加油量和平均加油量
            let totalFuelQuantity = 0; // 初始化总加油量
            console.log(this.avgList)
// 遍历筛选后的集合，累加 fuelQuantity
            this.avgList.forEach(station => {
              totalFuelQuantity += station.fuelQuantity || 0; // 避免 fuelQuantity 为 undefined 的情况
            });
// 计算平均加油量
            this.avgOil = this.avgList.length > 0
              ? totalFuelQuantity / this.avgList.length
              : 0; // 避免除以 0 的情况





            if (this.avgOil !== 0) {
              // this.form.days = totalOilUsed / this.avgOil;
              this.form.days = Math.floor(totalOilUsed / this.avgOil);

            } else {
              this.form.days = 0;
            }
          });

        }

      );
    },
    fetchUsers() {
      this.loading=true;
      listUserNoPage().then(response => {
          this.filteredUsers = response.rows;
          this.loading = false;
        }
      );
    },
    workUserIdFormat(row, column) {

      let workUsers=  JSON.parse(row.extra2)
      if (!Array.isArray(workUsers)) {
        return '';
      }

      // 查找并格式化所有选中的用户
      const formattedUsers = workUsers.map(userId => {
        const user = this.filteredUsers.find(user => user.userId === userId);
        return user ? `${user.nickName}` : '';
      });
      console.log(formattedUsers)
      // 将所有格式化后的用户信息用逗号拼接
      let str= formattedUsers.filter(Boolean).join(', ');
      return str.split(',').map(name => name.trim()).join('<br>');
    },
    reportUserIdFormat(row, column) {
      const user = this.filteredUsers.find(user => user.userId === row.reportUserId);
      return user ? user.nickName : '';
    },
    formatCollectType(row, column, value) {
      return value === 0 ? '旧库' : value === 1 ? '新库' : '-'; // 格式化为文本
    },

    /** 查询油库列表 */
    getList() {
      this.loading = true;
      listDepot(this.queryParams).then(response => {
        this.depotList = response.rows;
        this.total = response.total;
        this.loading = false;
      });


    },
    // id字典翻译
    idFormat(row, column) {
      return this.selectDictLabel(this.idOptions, row.id);
    },
    // 名称字典翻译
    nameFormat(row, column) {
      return this.selectDictLabel(this.nameOptions, row.name);
    },
    // 收油数量字典翻译
    collectCountFormat(row, column) {
      return this.selectDictLabel(this.collectCountOptions, row.collectCount);
    },
    // 发油信息字典翻译
    sendInfoFormat(row, column) {
      return this.selectDictLabel(this.sendInfoOptions, row.sendInfo);
    },
    // 工作人员字典翻译

    // 异常情况字典翻译
    errorFormat(row, column) {
      return this.selectDictLabel(this.errorOptions, row.error);
    },
    // 创建人字典翻译
    createByFormat(row, column) {
      return this.selectDictLabel(this.createByOptions, row.createBy);
    },
    // 汇报人字典翻译

    // 创建时间字典翻译
    createTimeFormat(row, column) {
      return this.selectDictLabel(this.createTimeOptions, row.createTime);
    },
    // 修改人字典翻译
    updateByFormat(row, column) {
      return this.selectDictLabel(this.updateByOptions, row.updateBy);
    },
    // 修改时间字典翻译
    updateTimeFormat(row, column) {
      return this.selectDictLabel(this.updateTimeOptions, row.updateTime);
    },
    // extra1字典翻译
    extra1Format(row, column) {
      return this.selectDictLabel(this.extra1Options, row.extra1);
    },
    // extra2字典翻译
    extra2Format(row, column) {
      return this.selectDictLabel(this.extra2Options, row.extra2);
    },
    // extra3字典翻译
    extra3Format(row, column) {
      return this.selectDictLabel(this.extra3Options, row.extra3);
    },
    // extra4字典翻译
    extra4Format(row, column) {
      return this.selectDictLabel(this.extra4Options, row.extra4);
    },
    // 部门字典翻译
    deptIdFormat(row, column) {
      return this.selectDictLabel(this.deptIdOptions, row.deptId);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        collectCount: null,
        sendInfo: null,
        workUserId: null,
        error: null,
        createBy: null,
        reportUserId: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        extra1: null,
        extra2: null,
        extra3: null,
        extra4: null,
        deptId: null,
        info: null,
        collectWeight: null,
        days: null,
        selfInfo: null,
        sendJson: null,
        collectType: 0
      };
      this.reportOilDepotDetailList = [];

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fetchOilTanks()
      this.fetchKh()

      this.form.reportDate =new Date()
      this.open = true;
      this.title = "油库数据上报";
      let currentUser = this.$store.state.user;
      this.form.reportUserId = currentUser.userId

      this.form.name =this.formattedDate()
      this.addKhRow()
      this.addDensityRow()
    },
    formattedDate() {
      const year = this.currentDate.getFullYear();
      const month = String(this.currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(this.currentDate.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.fetchOilTanks()
      this.fetchKh()
      const id = row.id || this.ids
      getDepot(id).then(response => {
        this.form = response.data;
        if ( this.form.extra3){
          this.form.extra1=JSON.parse(this.form.extra3)

        }
        if ( this.form.extra4){
          this.form.sendJson=JSON.parse(this.form.extra4)

        }
        this.reportOilDepotDetailList = response.data.reportOilDepotDetailList;
        this.reportOilDepotDetailList.forEach(r => {
          r.tankStatus = r.tankStatus + '';

          const matchingTank = this.filterdOilTanks.find(tank => tank.id+'' === r.tankId+'');
          // 如果找到匹配的元素，将其 typeId 赋值给 r.tankType
          if (matchingTank) {
            r.tankType = matchingTank.typeId;
          }
        });

        this.open = true;
        this.title = "修改油库上报数据";
        this.form.workUsers = JSON.parse(response.data.extra2)

        if(!this.form.extra1){
          this.addKhRow()
        }


      });
    },
    /** 提交按钮 */
    submitForm() {
      this.validateDetailList({}, this.reportOilDepotDetailList, (error) => {
        if (error) {
          // 如果有错误，提示用户
          this.$message.error(error.message);
        } else {

          this.$refs["form"].validate(valid => {
            if (valid) {
              this.form.reportOilDepotDetailList = this.reportOilDepotDetailList;
              if (this.form.id != null) {
                updateDepot(this.form).then(response => {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addDepot(this.form).then(response => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            }
          });
        }
      })
    }
      ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除油库编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDepot(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
	/** 油罐信息详情序号 */
    rowReportOilDepotDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 油罐信息详情添加按钮操作 */
    handleAddReportOilDepotDetail() {
      let obj = {};
      obj.extra1 = "";
      obj.extra2 = "";
      obj.extra3 = "";
      obj.extra4 = "";
      obj.deptId = "";
      obj.tankId = "";
      obj.tankWeight = "";
      obj.tankHeight = "";
      obj.tankStatus = "";
      obj.sheetNo = "";
      this.reportOilDepotDetailList.push(obj);
    },
    /** 油罐信息详情删除按钮操作 */
    handleDeleteReportOilDepotDetail() {
      if (this.checkedReportOilDepotDetail.length == 0) {
        this.$alert("请先选择要删除的油罐信息详情数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.reportOilDepotDetailList.splice(this.checkedReportOilDepotDetail[0].index - 1, 1);
      }
    },
    /** 单选框选中数据 */
    handleReportOilDepotDetailSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.reportOilDepotDetail.clearSelection();
        this.$refs.reportOilDepotDetail.toggleRowSelection(selection.pop());
      } else {
        this.checkedReportOilDepotDetail = selection;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('depot/depot/export', {
        ...this.queryParams
      }, `depot_${new Date().getTime()}.xlsx`)

      // const queryParams = this.queryParams;
      // this.$confirm('是否确认导出所有油库数据项?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(() => {
      //     this.exportLoading = true;
      //     return exportDepot(queryParams);
      //   }).then(response => {
      //     this.download(response.msg);
      //     this.exportLoading = false;
      //   }).catch(() => {});
    }
  }
};
</script>
<style>
.text-center {
  text-align: center!important;
}
/* 让下拉选项内容居中 */
.center-select .el-select-dropdown__item {
  text-align: center;
  width: 100%;
}

/* 让选中后的数据居中 */
.center-select .el-input__inner {
  text-align: center !important; /* 确保选中内容居中 */
  width: 100%;
}


</style>
